package com.aier.utils;

import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 时间操作工具类
 */
@Repository
public class DateUtils {

    /**
     * 获取开始时间和结束时间的所有年月（201406格式），并返回一个列表
     * @return
     */
    public List<String> getAllYearAndMonth(LocalDate startDate, LocalDate endDate){
        List<String> yearAndMonthList = new ArrayList<>();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMM");
        yearAndMonthList.add(startDate.format(dateTimeFormatter));
        startDate = startDate.plus(1, ChronoUnit.MONTHS);
        while (!startDate.isAfter(endDate)){
            yearAndMonthList.add(startDate.format(dateTimeFormatter));
            startDate = startDate.plus(1, ChronoUnit.MONTHS);
        }
        String endYearMonth = endDate.format(dateTimeFormatter);
        if (!yearAndMonthList.contains(endYearMonth)){
            yearAndMonthList.add(endYearMonth);
        }
        return yearAndMonthList;
    }


    /**
     * 获取日期当前月的第一天
     * @param date
     * @return
     */
    public LocalDate getDateFirstDayOfMonth(LocalDate date){
        return date.with(TemporalAdjusters.firstDayOfMonth());
    }

    /**
     * 获取日期当前月的最后一天
     * @param date
     * @return
     */
    public LocalDate getDateLastDayOfMonth(LocalDate date){
        return date.with(TemporalAdjusters.lastDayOfMonth());
    }

    /**
     * 将字符串按指定格式转换为LocalDate对象
     * @param date
     * @param format
     * @return
     */
    public LocalDate getLocalDateByString(String date, String format){
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(format);
        return LocalDate.parse(date, dateTimeFormatter);
    }

    public static void main(String[] args) {
        DateUtils dateUtils = new DateUtils();
        LocalDate startDate = LocalDate.of(2023, 11, 2);
        LocalDate endDate = LocalDate.of(2024, 1, 31);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        System.out.println(dateUtils.getDateFirstDayOfMonth(endDate).format(dateTimeFormatter));
        System.out.println(dateUtils.getLocalDateByString("20240112","yyyyMMdd"));
    }
}
